<template>
  <div class='demo'>
    <div class="from">
      <h1>我是表单啊</h1>
      <button @click="open" style="font-size: .2rem;color: #00c244;">预览</button>

      <div v-if="ishow">
        <img :src="mapImage.image1" alt="">
        <img :src="mapImage.image2" alt="">
      </div>
    </div>
    <div class="mapbox" v-show="yulan">
      <div class="box">
        <div id="map1"></div>
        <div id="map2"></div>
      </div>
      <div class="yulan" v-show="false">
        <span style="font-size: 3rem">预览中</span>
      </div>
    </div>
  </div>
</template>
<script>
  import api from '../utils/api'
  import http from '../utils/http'
  import olMap from "ol/Map";
  import View from "ol/View";
  import VectorSources from 'ol/source/Vector';
  import {XYZ, Vector as VectorSource, OSM} from "ol/source";
  import * as olProj from "ol/proj";
  import {Image as ImageLayer, Heatmap as HeatmapLayer, Tile as TileLayer, Vector as VectorLayer} from "ol/layer";
  import ImageWMS from 'ol/source/ImageWMS';
  import WMTS from 'ol/source/WMTS';
  import WMTSTileGrid from 'ol/tilegrid/WMTS';
  import {Circle as CircleStyle, Fill, Stroke, Style, Text, Icon} from 'ol/style';
  import GeoJSON from "ol/format/GeoJSON";
  import MousePosition from 'ol/control/MousePosition';
  import {createStringXY} from 'ol/coordinate';
  import {getArea, getLength} from 'ol/sphere';
  import {Draw, Modify, Snap, DragBox, Select} from 'ol/interaction';
  import {LineString, Polygon} from 'ol/geom';
  import Overlay from 'ol/Overlay';
  import {unByKey} from 'ol/Observable';
  import {getWidth, getTopLeft} from 'ol/extent.js';
  import {platformModifierKeyOnly} from 'ol/events/condition';
  import {defaults as defaultControls, OverviewMap} from 'ol/control';
  export default {
    data() {
      return {
        center: [],
        gnqh: {},
        mapImage: {},
        ishow: false,
        yulan: false
      }
    },
    created() {
      this.$axios.get('/api/area/0000011')
        .then(res => {
          this.center = [res.data.mapConfig.lon, res.data.mapConfig.lat];
        })
        .catch(err => {
          alert("网络异常")
        })
    },
    mounted() {
    },
    methods: {
      open(){
        var then = this;
        (async function () {
          let res = await http.get(api.getLayers, {
            areaId: "0000011"
          })
          res.data.data.polygon.forEach(t => {
            if (t.name == '功能区划') {
              then.gnqh = t;
              then.yulan = true;
              setTimeout(function () {
                then.createMap();
              }, 500)
            }
          })
        })()
      },
      createMap(){
        var then = this, obj = {};
        let params = {
          'LAYERS': this.gnqh.layerName,
          'STYLES': this.gnqh.styleId,
          'CQL_FILTER': "[" + this.gnqh.cql + "]"
        };
        var gnqhLayer = new ImageLayer({
          source: new ImageWMS({
            crossOrigin: 'anonymous',
            url: this.gnqh.layerUrl,
            params: params,
            serverType: 'geoserver'
          })
        })
        var BaseMap = new TileLayer({
          source: new XYZ({
            crossOrigin: 'anonymous',
            url: 'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=bac73ffb71b5b713a658ee1ed8c7ffd9'
          })
        })
//        创建第一个地图
        var map1 = new olMap({
          target: "map1",
          layers: [
            new TileLayer({
              source: new OSM()
            })
          ],
          controls: defaultControls({
            attribution: false,
            zoom: false,
            rotate: false
          }).extend([new OverviewMap()]),
          view: new View({
            //设置中心点
            center: olProj.fromLonLat(this.center),
            zoom: 11
          })
        });
        var map2 = new olMap({
          target: "map2",
          layers: [
            new TileLayer({
              source: new OSM()
            })
          ],
          controls: defaultControls({
            attribution: false,
            zoom: false,
            rotate: false
          }).extend([new OverviewMap()]),
          view: new View({
            //设置中心点
            center: olProj.fromLonLat(this.center),
            zoom: 11
          })
        });
        map1.addLayer(BaseMap);
        map1.addLayer(gnqhLayer);

        map2.addLayer(BaseMap);
        map2.addLayer(gnqhLayer);
        //设置geojson样式
        let styleFunction = function () {
          return function (feature, resolution) {
            //点
            if (feature.getGeometry().getType() == 'Point') {
              if (feature.get('fillColor').indexOf('#') != -1) {
                var point = new Style({
                  image: new CircleStyle({
                    radius: feature.get("radius"),
                    fill: new Fill({
                      color: feature.get("fillColor")
                    }),
                    stroke: new Stroke({
                      color: feature.get("borderColor"),
                      width: feature.get("size")
                    })
                  }),
                  text: new Text({
                    font: '12px Calibri,sans-serif',
                    text: feature.get('text'),
                    fill: new Fill({
                      color: feature.get('fillColor')
                    }),
                    offsetY: 15,
                    stroke: new Stroke({
                      color: 'white',
                      width: 1
                    }),
                  })
                })
              } else {
                var point = new Style({
                  image: vm.addImage(feature, resolution),
                  text: new Text({
                    font: '12px Calibri,sans-serif',
                    text: feature.get('text'),
                    fill: new Fill({
                      color: feature.get('fillColor')
                    }),
                    offsetY: 15,
                    stroke: new Stroke({
                      color: 'white',
                      width: 1
                    }),
                  })
                })
              }
              return [point]
            }
            if (feature.getGeometry().getType() == 'MultiPoint') {
              var MultiPoint = new Style({
                image: new CircleStyle({
                  radius: 5,
                  fill: new Fill({
                    color: feature.get("fillColor")
                  }),
                  stroke: new Stroke({
                    color: feature.get("borderColor"),
                    width: feature.get("size")
                  })
                }),
                text: new Text({
                  font: '12px Calibri,sans-serif',
                  text: feature.get('text'),
                  fill: new Fill({
                    color: feature.get('fillColor')
                  }),
                  offsetY: 15,
                  stroke: new Stroke({
                    color: 'white',
                    width: 1
                  }),
                })
              })
              return [MultiPoint]
            }
            //面
            if (feature.getGeometry().getType() == 'MultiPolygon') {
              var MultiPolygon = new Style({
                stroke: new Stroke({
                  color: feature.get('borderColor'),
                  width: feature.get("size")
                }),
                fill: new Fill({
                  color: feature.get("fillColor")
                }),
                text: new Text({
                  font: '16px Calibri,sans-serif',
                  text: feature.get('text'),
                  fill: new Fill({
                    color: feature.get('textColor')
                  }),
                  stroke: new Stroke({
                    color: feature.get('textColor'),
                    width: 1
                  })
                })
              })
              return [MultiPolygon]
            }
            if (feature.getGeometry().getType() == 'Polygon') {
              var Polygon = new Style({
                stroke: new Stroke({
                  color: feature.get('borderColor'),
                  width: feature.get("size")
                }),
                fill: new Fill({
                  color: feature.get("fillColor")
                }),
                text: new Text({
                  font: '12px Calibri,sans-serif',
                  text: feature.get('text'),
                  fill: new Fill({
                    color: feature.get('borderColor')
                  }),
                  stroke: new Stroke({
                    color: 'white',
                    width: 3
                  }),
                })
              })
              return [Polygon]
            }
            //线
            if (feature.getGeometry().getType() == 'LineString') {
              var LineString = new Style({
                stroke: new Stroke({
                  color: feature.get('borderColor'),
                  width: feature.get("size") + 3
                }),
                text: new Text({
                  font: '12px Calibri,sans-serif',
                  text: feature.get('text'),
                  fill: new Fill({
                    color: 'white'
                  }),
                  stroke: new Stroke({
                    color: 'block',
                    width: 2
                  }),
                })
              })
              return [LineString]
            }
            //多线
            if (feature.getGeometry().getType() == 'MultiLineString') {
              var MultiLineString = new Style({
                stroke: new Stroke({
                  color: feature.get('borderColor'),
                  width: feature.get("size") + 3
                }),
                text: new Text({
                  font: '12px Calibri,sans-serif',
                  text: feature.get('text'),
                  fill: new Fill({
                    color: 'white'
                  }),
                  stroke: new Stroke({
                    color: 'block',
                    width: 2
                  }),
                })
              })
              return [MultiLineString]
            }
          }
        };
        let geojsonObject = {
          'type': 'FeatureCollection',
          'crs': {
            'type': 'name',
            'properties': {
              'name': 'EPSG:4326'
            }
          },
          'features': []
        };
        //设置geojson样式
//        第一个图层
        let map1vectorSource = new VectorSource({
          features: (new GeoJSON(
            {
              defaultDataProjection: 'EPSG:4326',
              featureProjection: 'EPSG:3857'
            }
          )).readFeatures(geojsonObject)
        });
        let map1Layer = new VectorLayer({
          source: map1vectorSource,
          style: styleFunction()
        });
        let map1sources = map1Layer.getSource();
        let map1arr = [
          {
            id: "line001",
            borderColor: "#FF8300",
            fillColor: "#FF8300",
            data: {},
            geojson: {
              coordinates: [[115.8771254, 40.53894864], [115.84826286, 40.53686475], [115.84522848, 40.53720941]],
              type: "LineString"
            }
          }
        ]
        map1arr.forEach((e => {
          map1sources.addFeatures(
            (new GeoJSON({
              defaultDataProjection: 'EPSG:4326',
              featureProjection: 'EPSG:3857'
            })).readFeatures({
              "id": e.id,
              "properties": {
                "name": e.name,
                "borderColor": e.borderColor,
                "fillColor": e.fillColor,
                "iconSrc": e.iconSrc,
                "size": e.size,
                "radius": 6,
                "text": e.name,
                "data": e.data,
                "textColor": e.textColor,
                'customid': e.id
              },
              'type': 'Feature',
              'geometry': e.geojson
            }))
        }));
        map1Layer.set("altitudeMode", "clampToGround");
        //如果图层上同时存在点线面的话 需要把点线的层级设置高一点
//        map1Layer.setZIndex(10)
        map1.addLayer(map1Layer);
//        第一个图层

//        第二个图层
        let map2vectorSource = new VectorSource({
          features: (new GeoJSON(
            {
              defaultDataProjection: 'EPSG:4326',
              featureProjection: 'EPSG:3857'
            }
          )).readFeatures(geojsonObject)
        });
        let map2Layer = new VectorLayer({
          source: map2vectorSource,
          style: styleFunction()
        });
        let map2sources = map2Layer.getSource();
        let map2arr = [
          {
            id: "line001",
            borderColor: "#FF8300",
            fillColor: "#FF8300",
            data: {},
            geojson: {
              coordinates: [[115.8771254, 40.53894864], [115.84826286, 40.53686475], [115.84522848, 40.53720941]],
              type: "LineString"
            }
          }
        ], animalFenbu = [];
        let map2pointdataarr = [[115.8771254, 40.53894864], [115.84826286, 40.53686475], [115.84522848, 40.53720941]]
        map2pointdataarr.forEach((t, ind) => {
          var z = {
            id: t + ind,
            name: '',
            borderColor: "#ffffff",
            fillColor: "#FF6600",
            data: {},
            geojson: {coordinates: [t[0], t[1]], type: "Point"}
          }
          animalFenbu.push(z)
        })
        animalFenbu.forEach((e => {
          map2sources.addFeatures(
            (new GeoJSON({
              defaultDataProjection: 'EPSG:4326',
              featureProjection: 'EPSG:3857'
            })).readFeatures({
              "id": e.id,
              "properties": {
                "name": e.name,
                "borderColor": e.borderColor,
                "fillColor": e.fillColor,
                "iconSrc": e.iconSrc,
                "size": e.size,
                "radius": 6,
                "text": e.name,
                "data": e.data,
                "textColor": e.textColor,
                'customid': e.id
              },
              'type': 'Feature',
              'geometry': e.geojson
            }))
        }));
        map2arr.forEach((e => {
          map2sources.addFeatures(
            (new GeoJSON({
              defaultDataProjection: 'EPSG:4326',
              featureProjection: 'EPSG:3857'
            })).readFeatures({
              "id": e.id,
              "properties": {
                "name": e.name,
                "borderColor": e.borderColor,
                "fillColor": e.fillColor,
                "iconSrc": e.iconSrc,
                "size": e.size,
                "radius": 6,
                "text": e.name,
                "data": e.data,
                "textColor": e.textColor,
                'customid': e.id
              },
              'type': 'Feature',
              'geometry': e.geojson
            }))
        }));
        map2Layer.set("altitudeMode", "clampToGround");
        //如果图层上同时存在点线面的话 需要把点线的层级设置高一点
//        map1Layer.setZIndex(10)
        map2.addLayer(map2Layer);
//        第二个图层


//        渲染地图图片
        var base64 = {}
        map1.once('rendercomplete', function () {
          let mapCanvas = document.createElement('canvas');
          let size = map1.getSize();
          mapCanvas.width = size[0];
          mapCanvas.height = size[1];
          let mapContext = mapCanvas.getContext('2d');
          Array.prototype.forEach.call(document.querySelectorAll('.ol-layer canvas'), function (canvas, i) {
            if (i == 0) {
              if (canvas.width > 0) {
                var opacity = canvas.parentNode.style.opacity;
                mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
                var transform = canvas.style.transform;
                // Get the transform parameters from the style's transform matrix
                var matrix = transform.match(/^matrix\(([^\(]*)\)$/)[1].split(',').map(Number);
                // Apply the transform to the export map context
                CanvasRenderingContext2D.prototype.setTransform.apply(mapContext, matrix);
                mapContext.drawImage(canvas, 0, 0);
              }
            }
          });
          if (navigator.msSaveBlob) {
            navigator.msSaveBlob(mapCanvas.msToBlob(), 'map.png');
          } else {
            base64['image1'] = mapCanvas.toDataURL();
          }
        });
        map1.renderSync();
        map2.once('rendercomplete', function () {
          let mapCanvas = document.createElement('canvas');
          let size = map2.getSize();
          mapCanvas.width = size[0];
          mapCanvas.height = size[1];
          let mapContext = mapCanvas.getContext('2d');
          Array.prototype.forEach.call(document.querySelectorAll('.ol-layer canvas'), function (canvas, i) {
            if (i == 1) {
              if (canvas.width > 0) {
                var opacity = canvas.parentNode.style.opacity;
                mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
                var transform = canvas.style.transform;
                // Get the transform parameters from the style's transform matrix
                var matrix = transform.match(/^matrix\(([^\(]*)\)$/)[1].split(',').map(Number);
                // Apply the transform to the export map context
                CanvasRenderingContext2D.prototype.setTransform.apply(mapContext, matrix);
                mapContext.drawImage(canvas, 0, 0);
              }
            }
          });
          if (navigator.msSaveBlob) {
            navigator.msSaveBlob(mapCanvas.msToBlob(), 'map.png');
          } else {
            base64['image2'] = mapCanvas.toDataURL();
          }
        });
        map2.renderSync();
//        渲染地图图片


//       获取照片
        setTimeout(function () {
          then.mapImage = Object.assign({}, base64);
//          then.ishow = true
//          then.yulan = false
        }, 2000)
//       获取照片

      },
      addImage(feature, resolution) {
        let src = feature.get('iconSrc');
        let anchor = [0, 1];
        //根据图标文件名 设置定位点  地图上放置的图标更改文件名即可保持一致
        if (src != '') {
          if (src.indexOf('anchor_bottom_center') != -1) {
            anchor = [0.5, 1];
          } else if (src.indexOf('anchor_bottom_left') != -1) {
            anchor = [0, 1];
          } else if (src.indexOf('anchor_bottom_right') != -1) {
            anchor = [1, 1];
          } else if (src.indexOf('anchor_center_center') != -1) {
            anchor = [0.5, 0.5];
          } else if (src.indexOf('anchor_top_center') != -1) {
            anchor = [0.5, 0];
          } else if (src.indexOf('anchor_top_left') != -1) {
            anchor = [0, 0];
          } else if (src.indexOf('anchor_top_right') != -1) {
            anchor = [1, 0];
          }
          return new Icon({
            src: feature.get('iconSrc'),
            anchor: anchor,
          });
        }
      },
    }
  }
</script>
<style scoped>
  @import "../../static/css/demo.css";
</style>
